import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Row, Col, Tooltip } from 'antd';
import 'moment/locale/zh-cn';
import { PrimaryGhostC, TableC, SecondHeaderC, XYAxisChartsC } from '../../../../../../comps';
import '../../../index.less';
import colors from '../../../../../../css/colors';
import ChartsPie from './ChartsPie';
import { fixedNum } from '../../../../../../utils/utils';
import upPng from '../../../../../../assets/commom/up_arrow.png';
import downPng from '../../../../../../assets/commom/down_arrow.png';
import { exportFile } from '@/src/utils/commonFunc';

@connect(({ portfolioOptimizationM, loading }) => ({
  portfolioOptimizationM,
  loading,
}))
export default class TotalViewC extends PureComponent {
  state = {
    id: undefined, //分析结果的唯一id
    initWeightCharts: [], //初始权重charts数据
    optimizeWeightCharts: [], //初始权重charts数据
  };

  componentDidMount() {
    const {
      data: {
        config: { dataSource = [] },
      },
    } = this.props;
    this.setState({
      initWeightCharts: [
        ...dataSource.map((item) => {
          return { name: item.name, value: item.initWeight };
        }),
      ].splice(0, 10),
      optimizeWeightCharts: [
        ...dataSource.map((item) => {
          return { name: item.name, value: item.optimizeWeight };
        }),
      ].splice(0, 10),
    });
  }
  componentWillUnmount() {
    // 离开前清除models数据
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.state.id != nextProps.data.id) {
      //更新值
      const {
        data: {
          config: { dataSource = [] },
        },
      } = nextProps;
      this.setState({
        id: nextProps.data.id,
        initWeightCharts: [
          ...dataSource.map((item) => {
            return { name: item.name, value: item.initWeight };
          }),
        ].splice(0, 10),
        optimizeWeightCharts: [
          ...dataSource.map((item) => {
            return { name: item.name, value: item.optimizeWeight };
          }),
        ].splice(0, 10),
      });
    }
  }

  performCompTable = () => {
    //组合绩效对比对应的表格
    const {
      data: {
        performComp: { columns = [], dataSource = [] },
      },
    } = this.props;
    columns &&
      columns.map((item, index) => {
        if (item.key == 'initConfig') {
          item.type = 'number';
        }
        item.width = '33.33%';
        if (item.key == 'index') {
          item.render = (text) => {
            if (text == '平均收益') {
              return (
                <span>
                  {text}&nbsp;
                  <Tooltip title={'分析区间内的日平均收益'}>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </span>
              );
            }
            return text;
          };
        }
      });
    return <TableC columns={columns} dataSource={dataSource} rowKey='index' hidePage={true} />;
  };
  configTable = () => {
    //组合配置对应的表格
    const {
      data: {
        config: { columns = [], dataSource = [] },
      },
    } = this.props;
    columns &&
      columns.map((item) => {
        if (item.key != 'code' && item.key != 'name') {
          item.type = 'number';
          item.render = (text) => {
            return fixedNum(text, 2);
          };
        }
        if (item.key != 'code') {
          item.width = parseFloat(100 / columns.length) + '%';
        }
        if (item.key == 'weightDifference') {
          item.render = (text) => {
            const styleObj = {
              verticalAlign: 'top',
              paddingTop: '4px',
            };
            const styleObj1 = {
              verticalAlign: 'top',
              paddingTop: '5px',
            };
            if (text > 0) {
              return (
                <span style={{ color: colors.debtAndProfit.text[0] }}>
                  {text} <img src={upPng} style={styleObj}></img>
                </span>
              );
            } else if (text < 0) {
              return (
                <span style={{ color: colors.debtAndProfit.text[1] }}>
                  {text} <img src={downPng} style={styleObj1}></img>
                </span>
              );
            } else {
              return <span style={{ paddingRight: '11px' }}>{text} </span>;
            }
          };
        }
      });
    return <TableC columns={columns} dataSource={dataSource} rowKey='code' hidePage={true} scroll={dataSource.length > 8 ? { y: 264 } : {}} />;
  };

  export = () => {
    //导出文件 需要先请求token
    exportFile('thfx/optimization/downloadOptimizedAllocation', { id: this.state.id });
  };

  render() {
    const { initWeightCharts, optimizeWeightCharts } = this.state;
    const {
      data: { exposureComp = {} },
    } = this.props;
    var clientWidth = document.body.clientWidth;
    var minWidth = clientWidth - 220 - 100; //因柱状图开始很小 所以给个最小宽度
    return (
      <div style={{ paddingTop: '10px' }}>
        <div className='exportBtn'>
          <SecondHeaderC title={'组合配置'} />
          <div style={{ float: 'right' }}>
            <PrimaryGhostC title={'导出'} onClick={this.export} />
          </div>
        </div>
        {this.configTable()}
        <Row gutter={20} style={{ margin: 0 }}>
          <Col span={12} style={{ paddingTop: '20px' }}>
            <SecondHeaderC title={'初始权重'} />
            <div className='chartsClass'>
              <ChartsPie data={initWeightCharts} />
            </div>
          </Col>
          <Col span={12} style={{ paddingTop: '20px' }}>
            <SecondHeaderC title={'优化后权重'} />
            <div className='chartsClass'>
              <ChartsPie data={optimizeWeightCharts} />
            </div>
          </Col>
        </Row>
        {this.props.currentModel == '1' && (
          <div style={{ marginTop: '20px' }}>
            <SecondHeaderC title={'风险因子超额暴露度'} />
            <div style={{ minWidth: minWidth }}>
              <XYAxisChartsC
                series={exposureComp?.series}
                xAxis={exposureComp?.xAxis}
                height={455}
                yAxisUnit={['单位（%）', '']}
                type='bar'
                toolTipDataFormat={[(value) => value + '%']}
              />
            </div>
          </div>
        )}
        <div style={{ marginTop: '20px' }}>
          <SecondHeaderC title={'组合绩效对比'} />
        </div>
        {this.performCompTable()}
      </div>
    );
  }
}
